'''
不可修改
'''
import socket
import json
import threading
import threading
class client:
    '''负责接收message'''
    def __init__(self, get_message_from_client, server_ip='fe80::154b:b4c6:a10e:9932', port=65432):
        self.get_message_from_client = get_message_from_client

        # 初始化网络连接
        self.sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
        self.sock.connect((server_ip, port))

        # 启动接收线程
        receiver = threading.Thread(target=self.receive_messages, daemon=True)
        receiver.start()

        self.buffer = ""  # 缓冲区

    def send_message(self, message):
        self.sock.sendall(json.dumps(message).encode() + b'\n')


    def receive_messages(self):
        """接收服务器消息"""
        while True:
            try:
                data = self.sock.recv(1024).decode()
                self.buffer += data  # 数据存入缓冲区
                # 按分隔符分割消息
                while '\n' in self.buffer:
                    line, self.buffer = self.buffer.split('\n', 1)  # 分割出第一条完整消息
                    print(line)
                    if line:
                        self.get_message_from_client(json.loads(line))
            except:
                break
